package com.wuliu.system.service.applet.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wuliu.common.constant.OrderConstants;
import com.wuliu.common.core.domain.PageResult;
import com.wuliu.common.core.domain.entity.BasCust;
import com.wuliu.common.core.domain.entity.SysAppletUser;
import com.wuliu.common.exception.ServiceException;
import com.wuliu.common.utils.DateUtils;
import com.wuliu.common.utils.SecurityUtils;
import com.wuliu.common.utils.StringUtils;
import com.wuliu.common.utils.TencentLocationUtil;
import com.wuliu.system.domain.SysDeptFormula;
import com.wuliu.system.domain.TspOrder;
import com.wuliu.system.domain.TspOrderPre;
import com.wuliu.system.domain.TspTrack;
import com.wuliu.system.domain.bo.CalcOrderFeeBo;
import com.wuliu.system.domain.dto.applet.CustOrdersDto;
import com.wuliu.system.domain.dto.applet.QryOrderFeeDto;
import com.wuliu.system.domain.dto.applet.TspOrderPreDto;
import com.wuliu.system.domain.vo.applet.TspOrderPreVo;
import com.wuliu.system.mapper.*;
import com.wuliu.system.service.CommonService;
import com.wuliu.system.service.applet.AppletTspOrderPreService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.script.ScriptException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author realue
 * @version 1.0
 * @date 2023-10-30 16:03
 */
@Service
public class AppletTspOrderPreServiceImpl extends ServiceImpl<TspOrderPreMapper, TspOrderPre> implements AppletTspOrderPreService {

    @Resource
    private SysAppletUserMapper sysAppletUserMapper;
    @Resource
    private TspOrderMapper tspOrderMapper;
    @Resource
    private TspTrackMapper tspTrackMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private SysDeptFormulaMapper sysDeptFormulaMapper;
    @Resource
    private TspOrderPreMapper tspOrderPreMapper;

    /**
     * 创建预约单
     *
     * @param dto
     * @return
     */
    @Override
    public Integer createOrder(TspOrderPreDto dto) {
        if (dto.getReceiptFlag() == 1 && StringUtils.isEmpty(dto.getReceiptNo())) {
            throw new ServiceException("回单号不能为空");
        }
        BasCust basCust = SecurityUtils.getBasCust();
        TspOrderPre tspOrderPre = new TspOrderPre();
        BeanUtil.copyProperties(dto, tspOrderPre);
        if (StringUtils.isEmpty(dto.getOrderNo())) {
            tspOrderPre.setOrderNo(commonService.createOrderNo(basCust.getSysAccount(), 1, 1).get(0));
        }
        tspOrderPre.setId(IdUtil.randomUUID());
        tspOrderPre.setSysAccount(basCust.getSysAccount());
        tspOrderPre.setCreateBy(basCust.getCustName());
        tspOrderPre.setCreateTime(DateUtils.getNowDate());
        tspOrderPre.setStatus(OrderConstants.ORDER_PRE_STATUS_0);
        tspOrderPre.setCustId(basCust.getId());
        if (!Objects.isNull(dto.getGrabUserId())) {
            SysAppletUser user = sysAppletUserMapper.selectOne(new LambdaQueryWrapper<SysAppletUser>()
                    .eq(SysAppletUser::getUserId, dto.getGrabUserId())
                    .eq(SysAppletUser::getSysAccount, basCust.getSysAccount()));
            if (null != user) {
                tspOrderPre.setGrabUserId(user.getUserId());
                tspOrderPre.setGrabUserName(user.getUserName());
                tspOrderPre.setGrabUserNo(user.getUserNo());
                tspOrderPre.setGrabTime(DateUtils.getTime());
                tspOrderPre.setGrabUserTel(user.getMobile());
                tspOrderPre.setSrcDeptId(user.getDeptId());
                tspOrderPre.setSrcDeptNo(user.getDeptNo());
                tspOrderPre.setSrcDeptName(user.getDeptName());
                tspOrderPre.setStatus(OrderConstants.ORDER_PRE_STATUS_1);
            }
        }
        String address = dto.getSrcProvince() + dto.getSrcCity() + dto.getSrcDistrict() + dto.getSrcAddr();
        Map<String, String> map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrderPre.setSrcLng(MapUtils.getString(map, "lng"));
            tspOrderPre.setSrcLat(MapUtils.getString(map, "lat"));
        }
        address = dto.getDstProvince() + dto.getDstCity() + dto.getDstDistrict() + dto.getDstAddr();
        map = TencentLocationUtil.geoCoderRev(address);
        if (null != map) {
            tspOrderPre.setDstLng(MapUtils.getString(map, "lng"));
            tspOrderPre.setDstLat(MapUtils.getString(map, "lat"));
        }
        return tspOrderPreMapper.insertTspOrderPre(tspOrderPre);
    }

    /**
     * 取消下单
     *
     * @param id
     * @return
     */
    @Override
    public Integer cancelOrder(String id) {
        TspOrderPre tspOrderPre = tspOrderPreMapper.selectTspOrderPreById(id);
        if (tspOrderPre.getStatus() == OrderConstants.ORDER_PRE_STATUS_4) {
            throw new ServiceException("该订单已取消");
        }
        if (tspOrderPre.getStatus() != OrderConstants.ORDER_PRE_STATUS_1 && tspOrderPre.getStatus() != OrderConstants.ORDER_PRE_STATUS_0) {
            throw new ServiceException("当前状态不能取消");
        }
        //TODO 通知业务员

        TspOrderPre orderPre = new TspOrderPre();
        orderPre.setId(id);
        orderPre.setStatus(OrderConstants.ORDER_PRE_STATUS_4);
        return tspOrderPreMapper.updateTspOrderPre(orderPre);
    }

    /**
     * 查询当前客户寄件、收件信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<TspOrderPreVo> getCustOrders(CustOrdersDto dto) {
        BasCust cust = SecurityUtils.getBasCust();
        QueryWrapper<TspOrderPre> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_account", cust.getSysAccount());
        //1.我寄的 2.我收的
        if (dto.getType() == 1) {
            wrapper.eq("cust_id", cust.getId());
        } else if (dto.getType() == 2) {
            wrapper.eq("dst_tel", cust.getMobile());
        }
        if (StringUtils.isNotEmpty(dto.getKeyValue())) {
            wrapper.and(qw -> qw.like("src_name", dto.getKeyValue())
                    .or().like("dst_name", dto.getKeyValue())
                    .or().eq("order_no", dto.getKeyValue())
                    .or().eq("src_tel", dto.getKeyValue())
                    .or().eq("dst_tel", dto.getKeyValue()));
        }
        if (StringUtils.isNotEmpty(dto.getBeginDt())) {
            wrapper.ge("create_time", dto.getBeginDt());
        }
        if (StringUtils.isNotEmpty(dto.getEndDt())) {
            wrapper.le("create_time", dto.getEndDt() + " 23:59:59");
        }
        wrapper.orderByDesc("create_time");
        Page page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<TspOrderPre> orders = tspOrderPreMapper.selectList(wrapper);
        List<TspOrderPreVo> list = orders.stream().map(t -> {
            TspOrderPreVo tspOrderPreVo = new TspOrderPreVo();
            BeanUtil.copyProperties(t, tspOrderPreVo);
            return tspOrderPreVo;
        }).collect(Collectors.toList());
        return new PageResult<>(page, list);
    }

    /**
     * 查询运单路由
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<TspTrack> getTracks(String orderNo) {
        BasCust cust = SecurityUtils.getBasCust();
        long count = tspOrderMapper.selectCount(new LambdaQueryWrapper<TspOrder>()
                .eq(TspOrder::getSysAccount, cust.getSysAccount())
                .eq(TspOrder::getOrderNo, orderNo));
        if (count <= 0) {
            throw new ServiceException("运单号不存在,请重新输入");
        }
        return tspTrackMapper.selectList(new LambdaQueryWrapper<TspTrack>()
                .eq(TspTrack::getOrderNo, orderNo)
                .eq(TspTrack::getSysAccount, cust.getSysAccount())
                .orderByDesc(TspTrack::getOpTime));
    }

    /**
     * 运费查询
     *
     * @param dto
     * @return
     */
    @Override
    public BigDecimal qryFee(@Validated QryOrderFeeDto dto) {
        BasCust basCust = SecurityUtils.getBasCust();
        if (StringUtils.isAnyBlank(basCust.getProvince(), basCust.getCity())) {
            throw new ServiceException("请先完善用户省市信息");
        }
        if (Objects.isNull(dto.getCargoType())) {
            dto.setCargoType(OrderConstants.ORDER_CARGO_TYPE_1);
        }
        CalcOrderFeeBo calcOrderFeeBo = new CalcOrderFeeBo();
        BeanUtil.copyProperties(dto, calcOrderFeeBo);
        calcOrderFeeBo.setSrcProvince(basCust.getProvince());
        calcOrderFeeBo.setSrcCity(basCust.getCity());
        calcOrderFeeBo.setSysAccount(basCust.getSysAccount());
        return commonService.calcFee(calcOrderFeeBo);
    }
}
